package main

import (
	"encoding/json"
	"fmt"
	"io/ioutil"
	"log"
	"os"
	"path/filepath"
)

// OpenAPI 定义yml文档类似结构体
type OpenAPI struct {
	Paths map[string]map[string]Operation `yaml:"paths"`
}

type Operation struct {
	Tags []string `yaml:"tags"`
}

// LoadFile 加载文档
func LoadFile(jsonPath string) {
	currentDir, err := os.Getwd()
	if err != nil {
		log.Fatalf(Red+"Failed to get current directory: %v"+Reset, err)
	}
	persistPath := filepath.Join(currentDir, "api_map.json")

	// 读取json
	jsonFile, err := ioutil.ReadFile(jsonPath)
	if err != nil {
		log.Fatalf(Red+"File reading failure: %v"+Reset, err)
	}

	// 解析json
	var openAPI OpenAPI
	err = json.Unmarshal(jsonFile, &openAPI)
	if err != nil {
		log.Fatalf(Red+"Parsing file failed: %v"+Reset, err)
	}

	apiMap := make(map[string][]string)
	apiMap["jsonPath"] = []string{jsonPath}

	for path, methods := range openAPI.Paths {
		for method, operation := range methods {
			key := fmt.Sprintf("%s█%s", path, method)
			apiMap[key] = operation.Tags
		}
	}

	// 只在循环外部执行一次持久化存储
	err = SaveToFile(apiMap, persistPath)
	if err != nil {
		log.Fatalf(Red+"Failed to save apiMap: %v"+Reset, err)
	}
}

// SaveToFile 保存 apiMap 到文件
func SaveToFile(apiMap map[string][]string, filePath string) error {
	file, err := os.Create(filePath)
	if err != nil {
		return err
	}
	defer file.Close()

	encoder := json.NewEncoder(file)
	return encoder.Encode(apiMap)
}

type jsonFile struct {
	JsonPath []string            `json:"jsonPath"`
	Paths    map[string][]string `json:"paths"`
}

func getFP() string {
	jsonPath := "api_map.json"
	content, err := ioutil.ReadFile(jsonPath)
	if err != nil {
		log.Fatalf(Red+"Failed to read JSON file: %v"+Reset, err)
	}
	var jf jsonFile
	err = json.Unmarshal(content, &jf)
	if err != nil {
		log.Fatalf(Red+"Failed to unmarshal JSON: %v"+Reset, err)
	}
	fmt.Println("jsonPath:", jf.JsonPath)
	return jf.JsonPath[0]
}
